/*
    unisound_v03.c
    offer unisound module driver api realize
    designed by lunanting

    ---------------------
    2022-01-18 14:38:34
    first version

*/

#include "unisound_v03.h"
#include "bsp.h"
#include "aos/kernel.h"

static UNISOUND uns={0};


static void xp_uns_monitor_thread(void *arg);


/*
init unisound module
param:
    user_deal: uaer deal api regist, NULL= not regist
return:
    0=success
*/
int xp_uns_init(void (*user_deal)(int)){
    int sta=0;

    uns.uart.port=5;
    uns.uart.config.baud_rate=9600;
    uns.uart.config.data_width=DATA_WIDTH_8BIT;
    uns.uart.config.parity=NO_PARITY;
    uns.uart.config.stop_bits=STOP_BITS_1;
    uns.uart.config.flow_control=FLOW_CONTROL_DISABLED;
    uns.uart.config.mode=MODE_TX_RX;

    sta=hal_uart_init(&uns.uart);
    if(sta!=0){
        goto ERR;
    }
    if(user_deal!=NULL){
        uns.deal=user_deal;
    }
    aos_task_new("unisound_monitor",xp_uns_monitor_thread,NULL,3000);
    println("unisound uart init success!");
    return 0;
ERR:
    perr("unisound uart init fail. sta=%d.",sta);
    return -1;
}




/*
recive module msg monitor thread
*/
static void xp_uns_monitor_thread(void *arg){
    char buf[100];
    int rec_len=100;

    println("unisound monitor thread running !");
    aos_msleep(1000);
    xp_uart_rec_clear(&uns.uart);

    while(1){
        memset(buf,0,rec_len);
        rec_len=0;
        xp_uart_recive(&uns.uart,buf,3,&rec_len,100);
        if(rec_len==0){
            continue;
        }
        else if(strstr(buf,"xp")==NULL){
            perr("unisound cmd fault: %d %d %d.",buf[0],buf[1],buf[2]);
            continue;
        }
        if(uns.deal!=NULL){
            uns.deal(buf[2]);
        }
        else{
            println("unisound cmd id: %d.",buf[2]);
        }

    }
}




/*
regist user deal api
param:
    deal: deal function
*/
void xp_uns_dealAPI_regist(void (*deal)(int)){
    uns.deal=deal;
    if(deal!=NULL){
        println("unisound module user deal api regist !");
    }
    else{
        println("unisound module user deal api clear !");
    }
}

//end of the file
